package com.mall.service

import com.mall.entity.Product
import com.mall.mapper.ProductMapper
import org.springframework.stereotype.Service
import java.math.BigDecimal

/**
 * 商品服务类
 */
@Service
class ProductService(private val productMapper: ProductMapper) {

    /**
     * 创建商品
     */
    fun create(product: Product) {
        // 添加基本验证
        if (product.name.isEmpty()) {
            throw Exception("商品名称不能为空")
        }
        if (product.price.compareTo(BigDecimal.ZERO) <= 0) {
            throw Exception("商品价格必须大于0")
        }
        if (product.stock < 0) {
            throw Exception("商品库存不能小于0")
        }
        
        productMapper.insert(product)
    }

    /**
     * 根据ID获取商品
     */
    fun getById(id: Long): Product {
        return productMapper.findById(id) ?: throw Exception("商品不存在")
    }

    /**
     * 更新商品信息
     */
    fun update(product: Product) {
        productMapper.update(product)
    }

    /**
     * 删除商品
     */
    fun delete(id: Long) {
        productMapper.delete(id)
    }

    /**
     * 获取商品列表
     */
    fun list(page: Int, pageSize: Int): Map<String, Any> {
        val offset = (page - 1) * pageSize
        val products = productMapper.findAll(offset, pageSize)
        val total = productMapper.count()

        return mapOf(
            "data" to products,
            "total" to total
        )
    }
}